#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
配置管理模块

支持从环境变量、配置文件等多种方式读取配置
"""

import os
import json
from pathlib import Path
from typing import Dict, Any, Optional, Union
from dataclasses import dataclass, field
import logging

from .clean_converter import ConversionConfig, FileManagementConfig, ObsUploadConfig

logger = logging.getLogger(__name__)

class ConfigLoader:
    """配置加载器"""
    
    @staticmethod
    def from_env() -> ConversionConfig:
        """从环境变量加载配置"""
        # 文件管理配置
        file_management = FileManagementConfig(
            keep_work_files=os.getenv('KEEP_WORK_FILES', 'false').lower() == 'true',
            debug_mode=os.getenv('DEBUG_MODE', 'false').lower() == 'true'
        )
        
        # OBS上传配置
        obs_upload = ObsUploadConfig(
            enabled=os.getenv('OBS_UPLOAD_ENABLED', 'false').lower() == 'true',
            obs_config={
                "access_key": os.getenv('OBS_ACCESS_KEY'),
                "secret_key": os.getenv('OBS_SECRET_KEY'),
                "endpoint": os.getenv('OBS_ENDPOINT'),
                "bucket": os.getenv('OBS_BUCKET'),
                "region": os.getenv('OBS_REGION')
            } if os.getenv('OBS_ACCESS_KEY') else None,
            upload_types=os.getenv('OBS_UPLOAD_TYPES', 'image').split(','),
            storage_prefix=os.getenv('OBS_STORAGE_PREFIX', 'md'),
            replace_links=os.getenv('OBS_REPLACE_LINKS', 'true').lower() == 'true',
            remove_local_image_links=os.getenv('OBS_REMOVE_LOCAL_IMAGE_LINKS', 'true').lower() == 'true'
        )
        
        return ConversionConfig(
            work_temp_dir=os.getenv('WORK_TEMP_DIR'),
            file_management=file_management,
            obs_upload=obs_upload,
            log_level=os.getenv('LOG_LEVEL', 'INFO')
        )
    
    @staticmethod
    def from_file(config_path: Union[str, Path]) -> ConversionConfig:
        """从配置文件加载配置"""
        config_path = Path(config_path)
        
        if not config_path.exists():
            raise FileNotFoundError(f"配置文件不存在: {config_path}")
        
        try:
            with open(config_path, 'r', encoding='utf-8') as f:
                if config_path.suffix.lower() == '.json':
                    config_data = json.load(f)
                else:
                    # 简单的键值对格式
                    config_data = {}
                    for line in f:
                        line = line.strip()
                        if line and not line.startswith('#') and '=' in line:
                            key, value = line.split('=', 1)
                            config_data[key.strip()] = value.strip()
            
            return ConfigLoader._parse_config_data(config_data)
            
        except Exception as e:
            logger.error(f"读取配置文件失败: {e}")
            raise
    
    @staticmethod
    def _parse_config_data(config_data: Dict[str, Any]) -> ConversionConfig:
        """解析配置数据"""
        # 文件管理配置
        file_management = FileManagementConfig(
            keep_work_files=ConfigLoader._parse_bool(config_data.get('keep_work_files', False)),
            debug_mode=ConfigLoader._parse_bool(config_data.get('debug_mode', False))
        )
        
        # OBS配置
        obs_config = None
        if config_data.get('obs_access_key'):
            obs_config = {
                "access_key": config_data.get('obs_access_key'),
                "secret_key": config_data.get('obs_secret_key'),
                "endpoint": config_data.get('obs_endpoint'),
                "bucket": config_data.get('obs_bucket'),
                "region": config_data.get('obs_region')
            }
        
        obs_upload = ObsUploadConfig(
            enabled=ConfigLoader._parse_bool(config_data.get('obs_upload_enabled', False)),
            obs_config=obs_config,
            upload_types=config_data.get('obs_upload_types', 'image').split(','),
            storage_prefix=config_data.get('obs_storage_prefix', 'md'),
            replace_links=ConfigLoader._parse_bool(config_data.get('obs_replace_links', True)),
            remove_local_image_links=ConfigLoader._parse_bool(config_data.get('obs_remove_local_image_links', True))
        )
        
        return ConversionConfig(
            work_temp_dir=config_data.get('work_temp_dir'),
            file_management=file_management,
            obs_upload=obs_upload,
            log_level=config_data.get('log_level', 'INFO')
        )
    
    @staticmethod
    def _parse_bool(value) -> bool:
        """解析布尔值"""
        if isinstance(value, bool):
            return value
        if isinstance(value, str):
            return value.lower() in ('true', '1', 'yes', 'on')
        return bool(value)

def create_config_template(output_path: Union[str, Path]):
    """创建配置文件模板"""
    template = """# 转换引擎配置文件模板

# 工作目录配置
work_temp_dir=/tmp/converter_engine

# 文件管理配置
keep_work_files=false
debug_mode=false

# 日志级别 (DEBUG, INFO, WARNING, ERROR)
log_level=INFO

# OBS上传配置
obs_upload_enabled=false
obs_access_key=your_access_key
obs_secret_key=your_secret_key
obs_endpoint=obs.cn-north-4.myhuaweicloud.com
obs_bucket=your_bucket
obs_region=cn-north-4
obs_upload_types=image
obs_storage_prefix=md
obs_replace_links=true
obs_remove_local_image_links=true
"""
    
    output_path = Path(output_path)
    output_path.write_text(template, encoding='utf-8')
    print(f"配置文件模板已创建: {output_path}")

def create_json_config_template(output_path: Union[str, Path]):
    """创建JSON配置文件模板"""
    template = {
        "work_temp_dir": "/tmp/converter_engine",
        "file_management": {
            "keep_work_files": False,
            "debug_mode": False
        },
        "obs_upload": {
            "enabled": False,
            "obs_config": {
                "access_key": "your_access_key",
                "secret_key": "your_secret_key",
                "endpoint": "obs.cn-north-4.myhuaweicloud.com",
                "bucket": "your_bucket",
                "region": "cn-north-4"
            },
            "upload_types": ["image"],
            "storage_prefix": "md",
            "replace_links": True,
            "remove_local_image_links": True
        },
        "log_level": "INFO"
    }
    
    output_path = Path(output_path)
    with open(output_path, 'w', encoding='utf-8') as f:
        json.dump(template, f, indent=2, ensure_ascii=False)
    print(f"JSON配置文件模板已创建: {output_path}")

# 便捷函数
def load_config_from_env() -> ConversionConfig:
    """从环境变量加载配置"""
    return ConfigLoader.from_env()

def load_config_from_file(config_path: Union[str, Path]) -> ConversionConfig:
    """从文件加载配置"""
    return ConfigLoader.from_file(config_path)

def load_config_auto() -> ConversionConfig:
    """自动加载配置（优先级：配置文件 > 环境变量 > 默认值）"""
    # 查找配置文件
    config_files = [
        "converter_config.json",
        "converter_config.conf", 
        "config.json",
        ".env"
    ]
    
    for config_file in config_files:
        if Path(config_file).exists():
            try:
                logger.info(f"使用配置文件: {config_file}")
                return ConfigLoader.from_file(config_file)
            except Exception as e:
                logger.warning(f"读取配置文件 {config_file} 失败: {e}")
                continue
    
    # 如果没有配置文件，使用环境变量
    logger.info("使用环境变量配置")
    return ConfigLoader.from_env() 